package com.test.myestest.config;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class ESConfig {
    @Value("${es.username}")
    private String username;

    @Value("${es.password}")
    private String password;

    @Value("${es.nodes}")
    private String nodes;

    @Bean
    public ElasticsearchClient elasticsearchClient() {

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials(username, password));


        // 创建低级 REST 客户端
        RestClient restClient = RestClient.builder(init(nodes))
                .setHttpClientConfigCallback(httpClientBuilder ->
                        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                )
                .build();

        // 创建 Elasticsearch 客户端
        ElasticsearchClient client = new ElasticsearchClient(
                new RestClientTransport(
                        restClient,
                        new JacksonJsonpMapper()
                )
        );
        return client;
    }

    private HttpHost[] init(String list) {
        List<HttpHost> result = new ArrayList<>();
        if (!list.contains(",")) {
            String[] hostPort = list.split(":");
            HttpHost httpHost = new HttpHost(hostPort[0], Integer.parseInt(hostPort[1]), HttpHost.DEFAULT_SCHEME_NAME);
            result.add(httpHost);
        } else {
            String[] hosts = list.split(",");
            for (int i = 0; i < hosts.length; i++) {
                String[] hostPort = hosts[i].split(":");
                HttpHost httpHost = new HttpHost(hostPort[0], Integer.parseInt(hostPort[1]), HttpHost.DEFAULT_SCHEME_NAME);
                result.add(httpHost);
            }
        }

        HttpHost[] arr = new HttpHost[result.size()];
        for (int i = 0; i < result.size(); i++) {
            arr[i] = result.get(i);
        }
        return arr;
    }

}